import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:tracker/common/enums/user_type_enum.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/pages/login/model/login_resp.dart';
import 'package:tracker/provider/global_provider.dart';
import 'package:tracker/router/router_manager.dart';
import 'package:tracker/theme/app_theme.dart';
import 'package:tracker/utils/toast_utils.dart';

/// 代理商登录 页面
class AgentLoginPage extends ConsumerStatefulWidget {
  const AgentLoginPage({super.key});

  @override
  ConsumerState<AgentLoginPage> createState() => _AgentLoginPageState();
}

class _AgentLoginPageState extends ConsumerState<AgentLoginPage> {
  final _formKey = GlobalKey<FormState>();
  final _usernameController = TextEditingController();
  final _passwordController = TextEditingController();
  final textColor = Colors.black;

  _doLogin() async {
    // 校验表单
    if (_formKey.currentState!.validate()) {
      // 验证通过提交数据
      var loginData = {
        'type': '1',
        'username': _usernameController.text,
        'password': _passwordController.text,
      };
      ToastUtils.showLoading();
      var res = await post<LoginResp, LoginResp>('/app/user/login', data: loginData, decodeType: LoginResp());
      res.when(success: (model) {
        ToastUtils.dismissLoading();
        if (model.code == 200) {
          ToastUtils.showToast('登录成功');
          SpUtil.putObject('loginData', model.data!);
          SpUtil.putBool('isLogin', true);
          ref.read(userTypeProvider.notifier).state = UserTypeEnum.fromValue(model.data!.type!);
          // 跳转到登录页
          context.go('/');
        } else {
          ToastUtils.showToast(model.msg ?? '登录失败');
        }
        XLogger.debug('登录成功');
      }, failure: (String msg, int code) {
        XLogger.error('登录失败 code: $code msg: $msg');
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        // 返回按钮的颜色
        iconTheme: const IconThemeData(color: Colors.black),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            // 标题
            Container(
              alignment: Alignment.topLeft,
              margin: const EdgeInsets.only(
                left: 20,
              ),
              child: const Text(
                '代理商登录',
                style: TextStyle(
                  fontSize: 24,
                ),
              ),
            ),
            const SizedBox(
              height: 60,
            ),
            // 表单
            Container(
              margin: const EdgeInsets.only(left: 20, right: 20),
              child: Form(
                key: _formKey,
                child: Column(
                  children: [
                    // 账号
                    TextFormField(
                      controller: _usernameController,
                      style: TextStyle(color: textColor),
                      decoration: InputDecoration(
                        hintText: "请输入代理商账号",
                        hintStyle: TextStyle(
                          fontSize: 15,
                          color: AppTheme.themeConfig.infoTextColor,
                        ),
                        // 调整内边距
                        contentPadding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 16.0),
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(32),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(32),
                          borderSide: BorderSide(
                            color: AppTheme.themeConfig.primaryColor,
                          ),
                        ),
                      ),
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return '请输入账号';
                        }
                        return null;
                      },
                    ),
                    const SizedBox(
                      height: 20,
                    ),
                    TextFormField(
                      controller: _passwordController,
                      obscureText: true,
                      style: TextStyle(color: textColor),
                      decoration: InputDecoration(
                        hintText: "请输入密码",
                        hintStyle: TextStyle(
                          fontSize: 15,
                          color: AppTheme.themeConfig.infoTextColor,
                        ),
                        // 调整内边距
                        contentPadding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 16.0),
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(32),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(32),
                          borderSide: BorderSide(
                            color: AppTheme.themeConfig.primaryColor,
                          ),
                        ),
                      ),
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return '请输入密码';
                        }
                        return null;
                      },
                    ),
                    const SizedBox(
                      height: 20,
                    ),
                    // 登录按钮
                    SizedBox(
                      width: double.infinity,
                      height: 50,
                      child: ElevatedButton(
                        onPressed: () {
                          // 校验表单
                          _doLogin();
                        },
                        style: ButtonStyle(
                          shape: MaterialStateProperty.all(
                            RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(32),
                            ),
                          ),
                          backgroundColor: MaterialStateProperty.all(AppTheme.themeConfig.primaryColor),
                        ),
                        child: const Text(
                          "登录",
                          style: TextStyle(color: Colors.white),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }
}
